/*
 * @描述: 
 * @创建者: kilomChou
 * @Date: 2021-05-03 11:50:08
 * @最后编辑: kilomChou
 * @LastEditTime: 2021-05-06 08:37:29
 */
import { _decorator, Component, Node, Sprite, UITransform, lerp } from 'cc';
import { VSnake } from '../../common/data/XlsxVo';
import { ISize } from '../../common/core/vec2/Vec2';
import { GameApp } from '../GameApp';
import { SnakeMod } from '../model/SnakeMod';
import { WorldMod } from '../model/WorldMod';
const { ccclass, property } = _decorator;

@ccclass('WorldMgr')
export class WorldMgr extends Component {

    @property(Node)
    bg: Node
    bgTran: UITransform
    cellSize: ISize;

    onLoad() {
        GameApp.worldMgr = this;
    }

    start() {
        this.bgTran = this.bg.getComponent(UITransform);
        let cell = this.bg.getComponent(Sprite).spriteFrame;
        this.cellSize = { w: cell.width, h: cell.height };
    }

    update(dt: number) {
        this.updateBg();
        this.updateCamera(dt);
    }

    /** 根据屏幕焦点更新摄像机位置 */
    updateCamera(dt: number) {
        let snakeNode = SnakeMod.getSnakeNodeById(WorldMod.focusSnakeNodeId);
        if (snakeNode && snakeNode.node) {
            let smooth = dt * 20;
            let scale = lerp(this.node.scale.x, 2 - (snakeNode.node.scale.x - VSnake.cfg.initWidth) / 100, smooth);
            this.node.setScale(scale, scale);
            let { x, y } = snakeNode.node.position;
            let cam = GameApp.mainCamera.node;
            cam.setPosition(lerp(cam.position.x, x * scale, smooth), lerp(cam.position.y, y * scale, smooth));
        }
    }

    /** 根据摄像机位置更新背景的大小和位置 */
    updateBg() {
        let { x, y } = this.node.position;
        let { x: scaleX, y: scaleY } = this.node.scale;
        let { w: cellW, h: cellH } = this.cellSize;
        let { w, h } = WorldMod.worldSize;
        let { x: camX, y: camY } = GameApp.mainCamera.node.position;
        let { width: cvW, height: cvH } = GameApp.mainCanvasSize;
        w *= 0.5;
        h *= 0.5;
        cvW = (cvW / scaleX) * 0.5;
        cvH = (cvH / scaleY) * 0.5;
        camX /= scaleX;
        camY /= scaleY;
        let startX = Math.max(x - w, camX - cvW);
        let startY = Math.max(y - h, camY - cvH);
        let endX = Math.min(x + w, camX + cvW);
        let endY = Math.min(y + h, camY + cvH);
        let firstX = startX / cellW;
        let firstY = startY / cellH;
        let floorX = Math.floor(firstX);
        let floorY = Math.floor(firstY);
        let extraW = (firstX - floorX) * cellW;
        let extraH = (firstY - floorY) * cellH;
        let bgW = Math.max(0, endX - startX + extraW);
        let bgH = Math.max(0, endY - startY + extraH);
        this.bg.setPosition(floorX * cellW, floorY * cellH);
        this.bgTran.setContentSize(bgW, bgH);
    }
}
